# ============================================================
# Set the Working Directory
# ============================================================
if (!requireNamespace("rstudioapi", quietly = TRUE)) {
  install.packages("rstudioapi")
}

# Set the working directory to the folder containing the script
if (rstudioapi::isAvailable()) {
  setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
  cat("Working directory set to:", getwd(), "\n")
} else {
  cat("rstudioapi is not available. Please set the working directory manually.\n")
}

# ============================================================
# Install and Load Required Packages
# ============================================================

# List of required packages
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  ggtext,         # For rich text labels in ggplot2
  tidyr,          # For data tidying (e.g., pivoting data)
  haven,          # For reading and writing SPSS, SAS, and Stata files
  plyr,           # For data manipulation
  dplyr,          # For data manipulation
  magrittr,       # For pipe operator (%>%)
  ggplot2,        # For plotting
  CGPfunctions,   # Custom functions for visualization (e.g., color palettes)
  scales,         # For scales and transformations in ggplot2
  ggh4x,          # For advanced ggplot2 functionality (e.g., faceting)
  cowplot,        # For multi-plot layouts
  stats,          # For statistical methods
  stringr,        # For string manipulation
  reshape2,       # For reshaping data
  directlabels,   # For direct labeling of ggplot2 plots
  ggstream,       # For streamgraphs
  patchwork,      # For combining ggplots
  ggrepel,        # For adding text labels to ggplots
  forcats,        # For working with factors
  ggh4x
)

# ============================================================
# Source Custom Constants and Functions
# ============================================================

# Define file paths for custom scripts
constants_file <- "./figures/constants.R"
functions_file <- "./figures/funcs.R"

# Check if the custom scripts exist before sourcing them
if (file.exists(constants_file)) {
  source(constants_file)
  message("Constants file sourced successfully.")
} else {
  stop("Error: Constants file not found. Please check the file path.")
}

if (file.exists(functions_file)) {
  source(functions_file)
  message("Functions file sourced successfully.")
} else {
  stop("Error: Functions file not found. Please check the file path.")
}

# ============================================================
# Load Data
# ============================================================

# Ensure the 'files_to_load' variable is defined before proceeding
if (exists("files_to_load")) {
  message("Loading data files...")

  # Load data using the custom load_data function
  data_list <- lapply(files_to_load, load_data)

  # Clean up the names by removing file extensions and assign data to global environment
  names(data_list) <- gsub("\\.dta$", "", names_datas)
  list2env(data_list, envir = .GlobalEnv)

  message("Data loaded successfully.")
} else {
  stop("Error: 'files_to_load' variable is not defined. Please ensure it is set correctly.")
}

# ============================================================
# Clean Datasets
# ============================================================

# Check if the file exists before sourcing it
if (file.exists("./figures/clean_files.R")) {
  source("./figures/clean_files.R")
  message("clean_files.R script executed successfully.")
} else {
  stop("Error: clean_files.R script not found. Please check the file path.")
}

# ============================================================
# Retrieve Main Images (Part of the Main Publication)
# ============================================================

# Check if the file exists before sourcing it
if (file.exists("./figures/main_graph.R")) {
  source("./figures/main_graph.R")
  message("main_graph.R script executed successfully.")
} else {
  stop("Error: main_graph.R script not found. Please check the file path.")
}

# ============================================================
# Retrieve Additional Images (Part of Online Appendix)
# ============================================================
# Check if the file exists before sourcing it
if (file.exists("./figures/appendix.R")) {
  source("./figures/appendix.R")
  message("appendix.R script executed successfully.")
} else {
  stop("Error: appendix.R script not found. Please check the file path.")
}
